package cn.com.dao;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import cn.com.entity.Notice;


public class NoticeDao {
	//公告的dao文件
private  SessionFactory sessionFac;
	
	public SessionFactory getSessionFac() {
		return sessionFac;
	}
	public void setSessionFac(SessionFactory sessionFac) {
		this.sessionFac = sessionFac;
	}
	Session session;
	Transaction tr;
	
	//查询所有的公告
	public List<Notice> selectAllNotice(){
		session=sessionFac.openSession();
		Query query=session.createQuery("from Notice");
		 List<Notice> list=query.list();
		 session.close();
		return list;
	}
	//查询一条公告
	public Notice selectOneNotice(Notice notice){
		session=sessionFac.openSession();
		Notice n=null;
		Query query=session.createQuery("from Notice where noticeid=?");
		query.setInteger(0, notice.getNoticeid());
		List<Notice> list=query.list();
		if(list!=null){
			 n=list.get(0);
		}
		session.close();
		return n;
	}
	//添加公告
	public boolean addNotice(Notice notice){
		session=sessionFac.openSession();
		tr=session.beginTransaction();
		boolean bool=false;
		try {
			//添加系统当前时间
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
			String date=sdf.format(new Date());   
			notice.setNoticepublishedtime(date);
			session.save(notice);
			tr.commit();
			bool=true;
			session.close();
			return bool;
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return bool;
		}
		
	}
	//更新公告
	public boolean updateNotice(Notice notice){
		session=sessionFac.openSession();
		tr=session.beginTransaction();
		boolean bool=false;
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
			String date=sdf.format(new Date());   
			notice.setNoticepublishedtime(date);
			session.update(notice);
			tr.commit();
			bool=true;
			session.close();
			return bool;
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return bool;
		}
		
	}
	//删除公告
	public boolean deleteNotice(Notice notice){
		session=sessionFac.openSession();
		tr=session.beginTransaction();
		boolean bool=false;
		try {
			session.delete(notice);
			tr.commit();
			bool=true;
			session.close();
			return bool;
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return bool;
		}
		
	}
}
